package com.ht.shop.controller;

import com.ht.shop.annotations.RequestMapping;
import com.ht.shop.pojo.CartItem;
import com.ht.shop.pojo.TbUser;
import com.ht.shop.service.CartService;
import com.ht.shop.service.impl.CartServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RequestMapping("/cart")
public class CartController {
    private CartService cartService = new CartServiceImpl();

    @RequestMapping("/create")
    public String addCart(HttpServletRequest request, HttpServletResponse response) {
        String goodId = request.getParameter("id");
        TbUser loginUser = (TbUser) request.getSession().getAttribute("loginUser");
        Long uid = loginUser.getId();
        int num =1;
        try {
            cartService.addCart(goodId,uid,num);
            response.setContentType("text/html;charset=utf-8");
            return "redirect:/cartSuccess.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/error/error.jsp";
        }

    }
    @RequestMapping("/show")
    public String show(HttpServletRequest request,HttpServletResponse response) {
//        if (request.getSession().getAttribute("cart") == null) {
            TbUser loginUser = (TbUser) request.getSession().getAttribute("loginUser");
            Long uid = loginUser.getId();
            List<CartItem> cartByUid = cartService.findCartByUid(uid);
            request.getSession().setAttribute("cart", cartByUid);
//        }
        return "forward:/cart.jsp";
    }
    @RequestMapping("/delete")
    public String  delete(HttpServletRequest request,HttpServletResponse response) {
        TbUser loginUser = (TbUser) request.getSession().getAttribute("loginUser");
        Long uid = loginUser.getId();
        cartService.deleteByUid(uid);
        request.getSession().setAttribute("cart",null);

        return "forward:/cart.jsp";
    }

}
